﻿using System;
using System.Collections.Generic;
using System.Text;
using com.dz.ht.common;
using System.Text.RegularExpressions;
using System.Web;

namespace com.dz.ht.components.book.site_1
{
    public class CollectBookManager:IBookObject
    {
        /// <summary>
        /// 获取首页所有的书籍
        /// </summary>
        /// <param name="i_book_default_url"></param>
        /// <returns></returns>
        public Dictionary<string, string> CollectDefaultBookList(string i_book_default_url)
        {
            return null;
        }

        /// <summary>
        /// 收集某个地址的所有小说详情地址
        /// </summary>
        /// <param name="i_book_list_url"></param>
        /// <returns>小说地址及小说名称</returns>
        public Dictionary<string, string> CollectBookList(string i_book_list_url)
        {
            string t_reg = "<span[^<>]*?class=[\'\"]?swbt[\'\"]?>.*?<a[^<>]*?hrefs*=s*[\'\"s]?[^\\d]*(\\d{1,})[^\"]*[\'\"]?[^<>]*?>(.*?)</a>.*? </span>";

            Dictionary<string, string> t_dic = null;
            try
            {
                string t_html = NetSiteCatchManager.ReadUrl(i_book_list_url, Encoding.GetEncoding("gb2312"));
                if (!string.IsNullOrEmpty(t_html))
                {
                    MatchCollection t_ma = Regex.Matches(t_html, t_reg, RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    if (t_ma != null && t_ma.Count > 0)
                    {
                        t_dic = new Dictionary<string, string>();
                        foreach (Match t_mc in t_ma)
                        {
                            if (t_mc.Groups.Count > 1)
                            {
                                if (!t_dic.ContainsKey(string.Format("http://www.qidian.com/book/{0}.aspx", t_mc.Groups[1].Value)))
                                {
                                    t_dic.Add(string.Format("http://www.qidian.com/book/{0}.aspx", t_mc.Groups[1].Value), t_mc.Groups[2].Value.ToString());
                                }
                            }
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                LogHelper.Error("收集小说列表地址失败" + ex.ToString());
            }

            return t_dic;
        }

        /// <summary>
        /// 收集某本小说详细信息
        /// </summary>
        /// <param name="i_book_url"></param>
        /// <returns></returns>
        public BookInfo CollectBookItem(string i_book_url)
        {
            BookInfo t_book_info = new BookInfo();
            t_book_info.BookUrl = i_book_url;
            long t_site_book_id = 0;
            Match t_mc_site_book_id = Regex.Match(i_book_url, "(\\d+)\\.", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            if (t_mc_site_book_id != null)
            {
                if (!long.TryParse(t_mc_site_book_id.Groups[1].Value.ToString(), out t_site_book_id))
                    t_site_book_id = 0;
            }
            t_book_info.ChapterUrl = string.Format("http://www.qidian.com/bookReader/{0}.aspx", t_site_book_id);
            try
            {
                string t_html = NetSiteCatchManager.ReadUrl(i_book_url, Encoding.GetEncoding("gb2312"));
                if (!string.IsNullOrEmpty(t_html))
                {
                    Match t_mc = Regex.Match(t_html, "<a.*?>.*?起点小说首页.*?</a>.*?<a.*?>(.*?)小说</a>.*?<a.*?>(.*?)</a>.*?<a.*?>(.*?)</a>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                    if (t_mc != null && t_mc.Groups.Count > 2)
                    {
                        t_book_info.BookCagegoryName = t_mc.Groups[1].Value.ToString();
                        t_book_info.BookSubCagegoryName = t_mc.Groups[2].Value.ToString();
                        t_book_info.BookName = t_mc.Groups[3].Value.ToString();
                    }
                    t_mc = Regex.Match(t_html, "<div[^<>]*?classs*=s*[\'\"s]?pic_box[\'\"]?[^<>]*?><a.*?><img[^<>]*?srcs*=s*[\'\"s]?([^\"]*)[\'\"]?[^<>]*?>[^<>]*?</a>.*?小说作者.*?<a.*?>(.*?)</a>.*?<div[^<>]*?classs*=s*[\'\"s]?data[\'\"]?[^<>]*?>.*?<div[^<>]*?classs*=s*[\'\"s]?txt[\'\"]?[^<>]*?>(.*?)</div>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    if (t_mc != null && t_mc.Groups.Count > 2)
                    {
                        t_book_info.ImageUrl = t_mc.Groups[1].Value.ToString();
                        if (!string.IsNullOrEmpty(t_book_info.ImageUrl))
                        {
                            if (t_book_info.ImageUrl.IndexOf("1.jpg") > -1)
                            {
                                t_book_info.IsExistsImage = false;
                            }
                            else
                            {
                                t_book_info.IsExistsImage = true;
                            }
                        }
                        t_book_info.AuthorName = t_mc.Groups[2].Value.ToString();
                        t_book_info.Description = NetSiteCatchManager.ReplaceContent(t_mc.Groups[3].Value.ToString());

                        t_mc = Regex.Match(t_html, "总点击[^<>]*?</b>(\\d{1,}).*?总推荐[^<>]*?</b>(\\d{1,}).*?总字数[^<>]*?</b>(\\d{1,}).*?小说性质[^<>]*?</b>(.*?)</td>.*?写作进程.*?</b>(.*?)</td>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                        if (t_mc != null && t_mc.Groups.Count > 4)
                        {
                            long t_click_count = 0;
                            if (!long.TryParse(t_mc.Groups[1].Value.ToString(), out t_click_count))
                                t_click_count = 0;
                            t_book_info.Click = t_click_count;
                            long t_collect = 0;
                            if (!long.TryParse(t_mc.Groups[2].Value.ToString(), out t_collect))
                                t_collect = 0;
                            t_book_info.Collect = t_collect;
                            long t_word_count = 0;
                            if (!long.TryParse(t_mc.Groups[3].Value.ToString(), out t_word_count))
                                t_word_count = 0;
                            t_book_info.WordsCount = 0;
                            if (!string.IsNullOrEmpty(t_mc.Groups[4].Value.ToString()) && t_mc.Groups[4].Value.ToString().ToLower().IndexOf("vip") > -1)
                            {
                                t_book_info.IsVip = true;
                            }
                            t_book_info.BookStatus = t_mc.Groups[5].Value.ToString();
                        }
                    }


                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("收集小说详情失败" + ex.ToString());
            }
            return t_book_info;
        }



        /// <summary>
        /// 收集某本书的所有章节
        /// </summary>
        /// <param name="i_chapter_list_url"></param>
        /// <returns></returns>
        public List<BookChapterInfo> CollectChapterList(string i_chapter_list_url)
        {
            List<BookChapterInfo> t_list_chapter = null;
            string t_volume_name = string.Empty;
            string t_sub_html = string.Empty;
            long t_site_book_id = 0;
            Match t_mc = Regex.Match(i_chapter_list_url, "(\\d+)\\.", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            if (t_mc != null)
            {
                if (!long.TryParse(t_mc.Groups[1].Value.ToString(), out t_site_book_id))
                    t_site_book_id = 0;
            }
            if (t_site_book_id == 0)
                return null;

            try
            {
                string t_html = NetSiteCatchManager.ReadUrl(i_chapter_list_url, Encoding.GetEncoding("gb2312"));
                if (!string.IsNullOrEmpty(t_html))
                {
                    t_list_chapter = new List<BookChapterInfo>();
                    string t_reg_volume = "<div[^<>]*?classs*=s*[\'\"s]?box_title[\'\"s]?><div[^<>]*?classs*=s*[\'\"s]?title[\'\"s]?><b>(.*?)</b>";

                    MatchCollection t_ma_volume = Regex.Matches(t_html, t_reg_volume, RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    if (t_ma_volume != null)
                    {
                        for (int index = 0; index < t_ma_volume.Count - 1; index++)
                        {
                            t_volume_name = t_ma_volume[index].Groups[1].Value.ToString();

                            t_volume_name = Regex.Replace(t_volume_name, "<a.*?>.*?</a>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);

                            t_sub_html = t_html.Substring(t_ma_volume[index].Index, (t_ma_volume[index + 1].Index - t_ma_volume[index].Index));

                            t_list_chapter.AddRange(ParseChapter(t_volume_name, t_sub_html, t_site_book_id));
                        }

                        t_volume_name = t_ma_volume[t_ma_volume.Count - 1].Groups[1].Value.ToString();

                        t_sub_html = t_html.Substring(t_ma_volume[t_ma_volume.Count - 1].Index);

                        t_list_chapter.AddRange(ParseChapter(t_volume_name, t_sub_html, t_site_book_id));
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(string.Format("收集小说:{0},章节失败:{1}", i_chapter_list_url, ex.ToString()));
            }
            //按跟新时间排序
            //if (t_list_chapter != null && t_list_chapter.Count > 0)
            //{
            //    t_list_chapter.Sort(delegate(BookChapterInfo t_a, BookChapterInfo t_b)
            //    {
            //        if (t_a.UpdateTime > t_b.UpdateTime)
            //            return 1;
            //        else if (t_a.UpdateTime == t_b.UpdateTime)
            //            return 0;
            //        return -1;
            //    });
            //}
            return t_list_chapter;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="i_volume_name"></param>
        /// <param name="i_text"></param>
        /// <param name="i_site_book_id"></param>
        /// <returns></returns>
        private List<BookChapterInfo> ParseChapter(string i_volume_name, string i_text, long i_site_book_id)
        {
            string t_reg_chapter = "<li[^<>]*?styles*=s*[\'\"s]?[^\"]*[\'\"]?[^<>]*?><a[^<>]*?hrefs*=s*[\'\"s]?([^\"]*,(\\d{1,})\\.aspx).*?title=[\'\"]?[字]?[数]?[：]?([\\d+]*).*?更新时间：(\\d{4}-[\\d{2}|\\d{1}]+-[\\d{2}|\\d{1}]+\\s[\\d{2}|\\d{1}]+:[\\d{2}|\\d{1}]+:[\\d{2}|\\d{1}]+).*?[\'\"]*[\'\"]\\s*?>(.*?)</a>";

            List<BookChapterInfo> t_chapter_list = new List<BookChapterInfo>();
            try
            {
                //匹配的集合
                MatchCollection t_ma = null;
                //章节字数
                int t_words_count = 0;
                i_volume_name = i_volume_name.Replace("&nbsp;", "");
                i_volume_name = Regex.Replace(i_volume_name, "(\\[.*?\\])", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                //更新时间
                DateTime t_update_time;

                bool t_is_vip = false;

                t_ma = Regex.Matches(i_text, t_reg_chapter, RegexOptions.IgnoreCase | RegexOptions.Compiled);

                if (t_ma != null && t_ma.Count > 0)
                {
                    foreach (Match t_mc in t_ma)
                    {

                        t_is_vip = false;
                        if (t_mc.Groups.Count >= 5)
                        {
                            BookChapterInfo t_book_chapter_info = new BookChapterInfo();
                            t_book_chapter_info.VolumeName = i_volume_name;
                            t_book_chapter_info.ChapterName = t_mc.Groups[5].Value.ToString();

                            if (!int.TryParse(t_mc.Groups[3].Value.ToString(), out t_words_count))
                                t_words_count = 0;
                            t_book_chapter_info.WordsCount = t_words_count;

                            if (!DateTime.TryParse(t_mc.Groups[4].Value.ToString(), out t_update_time))
                                t_update_time = DateTime.Now;
                            t_book_chapter_info.UpdateTime = t_update_time;

                            if (t_mc.Groups[1].Value.ToString().ToLower().IndexOf("vip") > -1)
                            {
                                t_is_vip = true;
                            }
                            t_book_chapter_info.IsVip = t_is_vip;
                            if (t_is_vip == false)
                            {
                                t_book_chapter_info.Comfrom = string.Format("http://files.qidian.com/Author{0}/{1}/{2}.txt", (i_site_book_id % 8 + 1), i_site_book_id, t_mc.Groups[2].Value.ToString());
                            }
                           
                            t_chapter_list.Add(t_book_chapter_info);
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                LogHelper.Error("收录章节失败" + ex.ToString());
            }
            return t_chapter_list;
        }

        /// <summary>
        /// 收集章节内容
        /// </summary>
        /// <param name="i_chapter_content_url"></param>
        /// <returns></returns>
        public string CollectChapterContent(string i_chapter_content_url)
        {
            if (string.IsNullOrEmpty(i_chapter_content_url))
                return string.Empty;
           
            if (!i_chapter_content_url.StartsWith("h"))
            {
                return GetChapterContentFromBaiDu(i_chapter_content_url);
            }
            string t_reg_content = "document.write\\('(.*?)\'\\)";
            string t_chapter_content = string.Empty;
            try
            {
                string t_html = NetSiteCatchManager.ReadUrl(i_chapter_content_url, Encoding.GetEncoding("gb2312"));

                if (!string.IsNullOrEmpty(t_html))
                {

                    Match t_mc_content = Regex.Match(t_html, t_reg_content, RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    if (t_mc_content != null && t_mc_content.Groups.Count > 0)
                    {
                        t_chapter_content = t_mc_content.Groups[1].Value.ToString();
                        t_chapter_content = NetSiteCatchManager.ReplaceContent(t_chapter_content);
                        t_chapter_content = string.Format("document.write('{0}');", t_chapter_content);
                    }
                }

                return t_chapter_content;
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取章节内容失败" + ex.ToString());
                return string.Empty;
            }
        }

        private string GetChapterContentFromBaiDu(string i_book_chapter_name)
        {
            /// <summary>
            /// 百度首页编码
            /// </summary>
            Encoding t_encoding = Encoding.GetEncoding("gb2312");
            string i_chapter_content_url = string.Format("http://www.baidu.com/s?wd={0}", HttpUtility.UrlEncode(i_book_chapter_name, t_encoding));
            string t_url = string.Empty;
            string t_chapter_name = i_book_chapter_name.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[1].ToString();
   
            if (t_chapter_name.IndexOf("章") > -1)
            {
                t_chapter_name = t_chapter_name.Substring(0,t_chapter_name.IndexOf("章")+1);
            }
            string t_chapter_content = string.Empty;
            string t_temp_chapter_content = string.Empty;
            ChapterCollectManager t_chapter_mgr = new ChapterCollectManager();

            try
            {
                string t_html = NetSiteCatchManager.ReadUrl(i_chapter_content_url, t_encoding);

                if (!string.IsNullOrEmpty(t_html))
                {
                    MatchCollection t_ma =Regex.Matches(t_html,"<h3\\s*?class=[\'\"]?t[\'\"]?><a[^<>]*?hrefs*=s*[\'\"]*([^\"\']*)[\'\"]*[^<>]*?>(.*?)</a>\\s*?</h3>",RegexOptions.IgnoreCase|RegexOptions.Compiled);               
                    if(t_ma==null || t_ma.Count<=0)
                        return string.Empty;
                    foreach (Match t_mc in t_ma)
                    {
                        if (t_mc.Groups.Count == 3)
                        {
                            t_url = t_mc.Groups[1].Value.ToString();

                           // t_chapter_content =t_chapter_mgr.GetChapterContent(t_url);
                            if (string.IsNullOrEmpty(t_chapter_content))
                            {
                                t_chapter_content = GetContent(t_url, t_chapter_name);
                                if (string.IsNullOrEmpty(t_chapter_content))
                                    continue;
                                else
                                    break;
                            }
                            else
                            {

                                break;
                            }
                        }
                    }
                  
                    t_chapter_content = NetSiteCatchManager.ReplaceContent(t_chapter_content);
                    t_chapter_content = string.Format("document.write('{0}');", t_chapter_content);
                    return t_chapter_content;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取网站代码失败" + ex.ToString());
            }
            return string.Empty;
        }

        private string GetContent(string i_url,string i_chapter_name)
        {
      
            Encoding t_encoding = Encoding.Default;
            int t_chapter_name_index = 0;
            string t_chapter_content = string.Empty;
            string t_tem_chapter_content=string.Empty;
            string t_charset = string.Empty;
            try
            {
                string t_html = NetSiteCatchManager.ReadUrl(i_url, t_encoding);

                if (!string.IsNullOrEmpty(t_html))
                {
                    t_chapter_name_index = t_html.LastIndexOf(i_chapter_name);
                    //不包含章节名称
                    if (t_chapter_name_index < 0)
                    {
                        Match t_mc_charset = Regex.Match(t_html, "<meta[^<>]*?charsets*=s*[\'\"]*([^\"\'\\s\\/]*)[\'\"]*[^<>]*?>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                        if (t_mc_charset != null)
                        {
                            t_charset = t_mc_charset.Groups[1].Value.ToString();

                            t_encoding = Encoding.GetEncoding(t_charset);

                            t_html = NetSiteCatchManager.ReadUrl(i_url, t_encoding);

                            t_chapter_name_index = t_html.LastIndexOf(i_chapter_name);

                            if (t_chapter_name_index < 0)
                                return string.Empty;
                        }
                    }

                    //t_html = t_html.Substring(t_chapter_name_index);

                    //查找章节内容
                    MatchCollection t_ma_content = Regex.Matches(t_html, "<div[^<>]*?>[&nbsp;\\s]*?([\u4e00-\u9fa5].*?)</div>", RegexOptions.IgnoreCase | RegexOptions.Compiled);

                    if (t_ma_content != null && t_ma_content.Count > 0)
                    {
                        foreach (Match t_mc_content in t_ma_content)
                        {
                            t_tem_chapter_content = ParseContent(t_mc_content.Groups[1].Value.ToString());

                            if (!string.IsNullOrEmpty(t_tem_chapter_content))
                                t_chapter_content = t_tem_chapter_content;
                        }

                    }
                    else
                    {
                        t_ma_content = Regex.Matches(t_html, "<td[^<>]*?>[&nbsp;\\s]*?([\u4e00-\u9fa5].*?)</td>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                        foreach (Match t_mc_content in t_ma_content)
                        {
                            t_tem_chapter_content = ParseContent(t_mc_content.Groups[1].Value.ToString());

                            if (!string.IsNullOrEmpty(t_tem_chapter_content))
                                t_chapter_content = t_tem_chapter_content;
                        }
                    }

                    return t_chapter_content;
                   
                }
                return string.Format("{0}({1})", t_chapter_content, i_url);
                //return t_chapter_content;

            }
            catch (Exception ex)
            {
                LogHelper.Error("获取页面内容失败" + ex.ToString());
                LogHelper.Info("站点编码:" + t_charset);
                return string.Empty;
            }
        }

        private string ParseContent(string i_conent)
        {
            if (string.IsNullOrEmpty(i_conent))
                return string.Empty;

            //替换掉所有的Html标记
            string   t_conent = Regex.Replace(i_conent, "<[^\u4e00-\u9fa5]>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled).Trim();

            if (t_conent.Length > 250)
                return i_conent;
            return string.Empty;
        }
    }
}
